package com.elong.businesstravel.modules.member;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpResponse;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.network.loopj.android.http.TextHttpResponseHandler;
import com.android.support.jhf.onClick.OnClickNetworkStatusListener;
import com.android.support.jhf.utils.ConfigManager;
import com.android.support.jhf.utils.DateUtils;
import com.android.support.jhf.utils.ImageUtil;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.dialog.CustomAlertDialog;
import com.elong.businesstravel.base.umeng.socialize.CustomShareDialog;
import com.elong.businesstravel.base.utils.AndroidManifestUtil;
import com.elong.businesstravel.base.utils.AppUserId;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.base.view.TitleNavBarView;
import com.elong.businesstravel.entitys.AccountInfo;
import com.elong.businesstravel.entitys.MemberManaged;
import com.elong.businesstravel.include.Version;
import com.elong.businesstravel.protocol.ProtocolDef;
import com.elong.businesstravel.protocol.login.LogoutRequest;
import com.elong.businesstravel.protocol.login.LogoutResponse;
import com.elong.businesstravel.protocol.login.MemberGetBonusRequest;
import com.elong.businesstravel.protocol.login.MemberGetBonusResponse;
import com.elong.businesstravel.protocol.login.MemberGetManagedRequest;
import com.elong.businesstravel.protocol.login.MemberGetManagedResponse;
import com.elong.businesstravel.protocol.login.MemberGetUseBonusRequest;
import com.elong.businesstravel.protocol.login.MemberGetUseBonusResponse;
import com.umeng.socialize.controller.RequestType;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.UMWXHandler;
import com.umeng.socialize.media.CircleShareContent;
import com.umeng.socialize.media.MailShareContent;
import com.umeng.socialize.media.QQShareContent;
import com.umeng.socialize.media.SinaShareContent;
import com.umeng.socialize.media.SmsShareContent;
import com.umeng.socialize.media.TencentWbShareContent;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.WeiXinShareContent;
import com.umeng.update.UmengUpdateAgent;
import com.umeng.update.UmengUpdateListener;
import com.umeng.update.UpdateResponse;
import com.umeng.update.UpdateStatus;

/**
 * 会员中心
 * 
 * @author lenovo
 * 
 */
public class MemberCenterActivity extends BaseActivity {
	/** 现金账户 */
	private TextView mCashAccountTextView;

	private MemberManaged mMemberManaged;

	private CustomShareDialog mCustomShareDialog;

	private String mShareTitleString;
	private String mShareContentString;
	private String mShareShortTitleString;
	private String mShareShortContentString;
	private Bitmap mShareBitmap;
	private String mAboutDataString;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_memeber_center);

		init();
	}

	@Override
	protected void init() {

		mShareTitleString = "推荐一个订酒店的神器----差旅通，注册时填写邀请码 "
				+ AppUserId.getUserId(mContext) + "就送30元红包";
		mShareShortTitleString = "推荐一个订酒店的神器----差旅通";
		mShareShortContentString = "注册时填写邀请码" + AppUserId.getUserId(mContext)
				+ "，就送30元红包";
		mShareContentString = "免费预订全国10万家酒店，返现奖励最高达30%";
		mShareBitmap = ImageUtil.drawable2Bitmap(getResources().getDrawable(
				R.drawable.ic_share));

		TextView userNameTextView = (TextView) findViewById(R.id.userNameTextView);
		String userNameString = SaveUserOperate.getLoginPhone(mContext);
		if (TextUtils.isEmpty(userNameString)) {
			userNameString = SaveUserOperate.getLoginNickName(mContext);
		}
		userNameTextView.setText(userNameString);
		TextView userIdTextView = (TextView) findViewById(R.id.userIdTextView);
		userIdTextView.setText(AppUserId.getUserId(mContext));

		/** 现金账户 */
		mCashAccountTextView = (TextView) findViewById(R.id.cashAccountTextView);

		setTitleNavBar();

		setListener();

		memberGetManaged();

		readAboutHtml();
	}

	/**
	 * 读取about的html问加你，替换%version@，为自己的版本号，替换%updateDate@为最后更新时间
	 */
	private void readAboutHtml() {
		try {
			InputStream inputStream = getAssets().open("html/aboutus.html");
			ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
			int len = -1;
			byte[] b = new byte[4096];
			while (-1 != (len = inputStream.read(b))) {
				byteArrayOutputStream.write(b, 0, len);
			}
			byteArrayOutputStream.flush();
			inputStream.close();
			mAboutDataString = byteArrayOutputStream.toString("UTF-8");
			mAboutDataString = mAboutDataString.replace("%version@",
					Version.versionName.substring(1));
			mAboutDataString = mAboutDataString.replace("%updateDate@",
					DateUtils.dateFormat(Version.productLastUpdateDate,
							"yyyyMMdd", "yyyy年MM月dd日"));
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void setListener() {
		ViewGroup redPurseLayout = (ViewGroup) findViewById(R.id.redPurseLayout);
		redPurseLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext, RedPurseActivity.class);
				startActivity(intent);
			}
		});

		ViewGroup enterpriseCertificationLayout = (ViewGroup) findViewById(R.id.enterpriseCertificationLayout);
		enterpriseCertificationLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext,
						EnterpriseCertificationActivity.class);
				intent.putExtra("MemberManaged", mMemberManaged);
				startActivity(intent);
			}
		});

		ViewGroup memberLevelLayout = (ViewGroup) findViewById(R.id.memberLevelLayout);
		memberLevelLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext, MemberLeveActivity.class);
				intent.putExtra("MemberManaged", mMemberManaged);
				startActivity(intent);
			}
		});
		ViewGroup bonusLayout = (ViewGroup) findViewById(R.id.bonusLayout);
		bonusLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				shareBouns();
			}
		});
		ViewGroup incomeStatementLayout = (ViewGroup) findViewById(R.id.incomeStatementLayout);
		incomeStatementLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext,
						MemberGetBonusActivity.class);
				startActivity(intent);
			}
		});
		ViewGroup useRecordLayout = (ViewGroup) findViewById(R.id.useRecordLayout);
		useRecordLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext,
						MemberGetUseBonusActivity.class);
				startActivity(intent);
			}
		});
		ViewGroup infoCenterLayout = (ViewGroup) findViewById(R.id.infoCenterLayout);
		infoCenterLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(mContext,
						MessageCenterActivity.class);
				startActivity(intent);
			}
		});
		ViewGroup aboutLayout = (ViewGroup) findViewById(R.id.aboutLayout);
		aboutLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(mContext, WebViewActivity.class);
				intent.putExtra("title", "关于我们");
				// intent.putExtra("url", ProtocolDef.ABOUT_URL);
				intent.putExtra("data", mAboutDataString);
				startActivity(intent);
			}
		});
		aboutLayout.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View arg0) {
				HandlerToastUI.getHandlerToastUI(mContext, AndroidManifestUtil
						.getMetaValue(mContext, "UMENG_CHANNEL"));
				return false;
			}
		});
		ViewGroup appRecommendLayout = (ViewGroup) findViewById(R.id.appRecommendLayout);
		ViewGroup updateAppLayout = (ViewGroup) findViewById(R.id.updateAppLayout);
		updateAppLayout.setOnClickListener(new OnClickNetworkStatusListener(
				mContext) {

			@Override
			public void onClickNetworkSucceed(View view) {
				showWaitDialog("正在加载...", null);
				UmengUpdateAgent.setUpdateAutoPopup(false);
				UmengUpdateAgent.setUpdateListener(new UmengUpdateListener() {
					@Override
					public void onUpdateReturned(int updateStatus,
							UpdateResponse updateInfo) {
						switch (updateStatus) {
						case UpdateStatus.Yes: // has update
							UmengUpdateAgent.showUpdateDialog(mContext,
									updateInfo);
							break;
						case UpdateStatus.No: { // has no update
							CustomAlertDialog customAlertDialog = new CustomAlertDialog(
									mContext, R.style.CustomAlertDialog);
							customAlertDialog.setMessage("您当前使用的版本已经是最新的");
							customAlertDialog.setLeftButton("确定",
									new OnClickListener() {

										@Override
										public void onClick(View arg0) {

										}
									});
							customAlertDialog.setRightButtonGone();
							customAlertDialog.show();
							// HandlerToastUI.getHandlerToastUI(mContext,
							// "没有更新");
							break;
						}
						case UpdateStatus.NoneWifi: // none wifi
							// HandlerToastUI.getHandlerToastUI(mContext,
							// "没有wifi连接， 只在wifi下更新");
							break;
						case UpdateStatus.Timeout: // time out
							HandlerToastUI.getHandlerToastUI(mContext, "网络超时");
							break;
						}

						hideWaitDialog();
					}

				});
				UmengUpdateAgent.forceUpdate(mContext);
			}

			@Override
			public void onClickNetworkFail(View view) {

			}
		});
	}

	private void shareBouns() {

		WeiXinShareContent weiXinShareContent = new WeiXinShareContent();
		weiXinShareContent.setShareContent(mShareContentString);
		weiXinShareContent.setTitle(mShareTitleString);
		weiXinShareContent.setShareImage(new UMImage(mContext, mShareBitmap));
		weiXinShareContent.setTargetUrl(ProtocolDef.SHARE_URL);
		weiXinShareContent.setAppWebSite(ProtocolDef.SHARE_URL);

		CircleShareContent circleShareContent = new CircleShareContent();
		circleShareContent.setShareContent(mShareContentString);
		circleShareContent.setTitle(mShareTitleString);
		circleShareContent.setShareImage(new UMImage(mContext, mShareBitmap));
		circleShareContent.setTargetUrl(ProtocolDef.SHARE_URL);
		circleShareContent.setAppWebSite(ProtocolDef.SHARE_URL);

		SinaShareContent sinaShareContent = new SinaShareContent();
		sinaShareContent.setShareContent(mShareTitleString
				+ mShareContentString + ",详情点击" + ProtocolDef.SHARE_URL);
		// sinaShareContent.setTitle(mShareContentString);
		sinaShareContent.setShareImage(new UMImage(mContext, mShareBitmap));
		sinaShareContent.setAppWebSite("http://www.lohoo.cn");

		// TencentWbShareContent tencentWbShareContent = new
		// TencentWbShareContent();
		// tencentWbShareContent.setShareContent(mShareTitleString
		// + mShareContentString + mShareUrlString);
		// // tencentWbShareContent.setTitle(mShareContentString);
		// tencentWbShareContent
		// .setShareImage(new UMImage(mContext, mShareBitmap));
		MailShareContent mailShareContent = new MailShareContent();
		mailShareContent.setShareContent(mShareTitleString + "，"
				+ mShareContentString + ",详情点击" + ProtocolDef.SHARE_URL);
		// mailShareContent.setTitle(mShareTitleString + mShareContentString +
		// mShareUrlString);
		// mailShareContent.setShareImage(new UMImage(mContext, mShareBitmap));
		// mailShareContent.setTargetUrl(mShareUrlString);
		// mailShareContent.setAppWebSite(mShareUrlString);

		QQShareContent qqShareContent = new QQShareContent();
		qqShareContent.setShareContent(mShareShortContentString);
		qqShareContent.setTitle(mShareShortTitleString);
		qqShareContent.setTargetUrl(ProtocolDef.SHARE_URL);
		qqShareContent.setAppWebSite(ProtocolDef.SHARE_URL);
		qqShareContent.setShareImage(new UMImage(mContext, mShareBitmap));
		// qqShareContent.set

		SmsShareContent smsShareContent = new SmsShareContent();
		smsShareContent.setShareContent(mShareTitleString + "，"
				+ mShareContentString + ",详情点击" + ProtocolDef.SHARE_URL);
		// smsShareContent.setTitle(mShareContentString);
		// smsShareContent.setShareImage(new UMImage(mContext, mShareBitmap));

		mCustomShareDialog = new CustomShareDialog(mContext,
				com.android.support.jhf.R.style.DialogFromDownToUp);
		mCustomShareDialog
				.setTitleMessage("邀请好友得30元红包",
						"好友在注册差旅通时填写您的专属邀请码" + AppUserId.getUserId(mContext)
								+ "您和好友都可得到30元的红包，可用于抵扣预付酒店房费。");

		mCustomShareDialog.setShareContent(weiXinShareContent,
				circleShareContent, sinaShareContent, mailShareContent,
				qqShareContent, smsShareContent);
		mCustomShareDialog.show();
	}

	@Override
	protected void setTitleNavBar() {

		TitleNavBarView titleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage("会员中心");
		titleNavBarView.setLeftDrawableImage(R.drawable.btn_title_back);
		titleNavBarView.setLeftButtonImageString(0, "返回", R.color.text_blue);
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 返回
				finish();
			}
		});
		titleNavBarView.setRightButtonImageString(0, "退出", R.color.text_blue);
		titleNavBarView.setRightButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 退出登录

				CustomAlertDialog customAlertDialog = new CustomAlertDialog(
						mContext, R.style.CustomAlertDialog);
				customAlertDialog.setMessage("是否退出当前账号?");
				customAlertDialog.setLeftButton("退出", new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						logout();
					}
				});
				customAlertDialog.setRightButton("取消", new OnClickListener() {

					@Override
					public void onClick(View arg0) {

					}
				});
				customAlertDialog.show();
			}
		});
	}

	private void logout() {
		NetworkClient.getNetworkClient().PostRequest(
				new LogoutRequest(mContext), new TextHttpResponseHandler() {

					@Override
					public void onSuccess(int statusCode, Header[] headers,
							String responseString, HttpResponse response) {
						AppUserId.setUserId(mContext, "");
						finish();
					}
				});
	}

	private void memberGetManaged() {
		NetworkClient.getNetworkClient().PostRequest(
				new MemberGetManagedRequest(mContext),
				new MemberGetManagedResponse() {

					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						HandlerPostUI.getHandlerPostUI(new Runnable() {

							@Override
							public void run() {
								mMemberManaged = memberManaged;
								mCashAccountTextView.setText("￥"
										+ memberManaged.uscore);
							}
						});
					}

				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (null != mCustomShareDialog) {
			mCustomShareDialog.onActivityResult(requestCode, resultCode, data);
		}
	}

}
